package com.ruoyi.project.system.service.impl;

import com.ruoyi.project.system.domain.*;
import com.ruoyi.project.system.service.*;
import com.aliyuncs.push.model.v20160801.PushResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 任务推送服务实现类
 * 
 * @author ruoyi
 * @date 2025-06-16
 */
@Service
public class TaskPushServiceImpl implements ITaskPushService {

    private static final Logger log = LoggerFactory.getLogger(TaskPushServiceImpl.class);

    @Autowired
    private ITasksService tasksService;

    @Autowired
    private ITaskRecipientsService taskRecipientsService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IAliyunPushService aliyunPushService;

    @Autowired
    private IReminderLogsService reminderLogsService;

    @Override
    public boolean pushMessageToTaskRecipients(Long taskId, String messageTitle, String messageContent,
            Map<String, Object> extras) {
        try {
            // 1. 获取任务信息
            Tasks task = tasksService.selectTasksById(taskId);
            if (task == null) {
                log.error("任务不存在，任务ID：{}", taskId);
                return false;
            }

            return pushMessageToTaskRecipients(task, messageTitle, messageContent, extras);
        } catch (Exception e) {
            log.error("推送任务消息失败，任务ID：{}，错误信息：{}", taskId, e.getMessage(), e);
            return false;
        }
    }

    @Override
    public boolean pushMessageToTaskRecipients(Tasks task, String messageTitle, String messageContent,
            Map<String, Object> extras) {
        try {
            // 0. 检查任务是否在有效期内
            if (!isTaskValid(task)) {
                log.warn("任务不在有效期内，跳过推送，任务ID：{}，任务标题：{}", task.getId(), task.getTitle());
                return false;
            }

            // 1. 获取任务接收人列表
            TaskRecipients recipientQuery = new TaskRecipients();
            recipientQuery.setTaskId(task.getId());
            List<TaskRecipients> recipients = taskRecipientsService.selectTaskRecipientsList(recipientQuery);

            if (recipients == null || recipients.isEmpty()) {
                log.warn("任务没有接收人，任务ID：{}", task.getId());
                return true; // 没有接收人也算成功
            }

            // 2. 准备推送内容
            String title = StringUtils.hasText(messageTitle) ? messageTitle : "任务通知：" + task.getTitle();
            String content = StringUtils.hasText(messageContent) ? messageContent : task.getDescription();

            // 3. 构建额外参数
            Map<String, Object> pushExtras = new HashMap<>();
            if (extras != null) {
                pushExtras.putAll(extras);
            }
            pushExtras.put("taskId", task.getId());
            pushExtras.put("taskTitle", task.getTitle());
            pushExtras.put("type", "TASK_NOTIFICATION");

            // 4. 批量推送给接收人
            boolean allSuccess = true;
            for (TaskRecipients recipient : recipients) {
                try {
                    // 获取用户信息
                    SysUser user = userService.selectUserById(recipient.getUserId());
                    if (user == null) {
                        log.warn("用户不存在，用户ID：{}", recipient.getUserId());
                        continue;
                    }

                    // 检查用户是否有设备ID（存储在remark字段中）
                    if (user.getRemark() == null || user.getRemark().trim().isEmpty()) {
                        log.warn("用户没有设备ID，用户ID：{}，用户名：{}", recipient.getUserId(), user.getUserName());
                        continue;
                    }

                    // 使用设备ID推送（从remark字段获取）
                    PushResponse pushResponse = aliyunPushService.pushMessageToDevice(
                            user.getRemark().trim(), // 使用remark字段存储的设备ID
                            title,
                            content,
                            pushExtras);

                    // 判断推送是否成功
                    boolean pushResult = pushResponse != null && pushResponse.getRequestId() != null;
                    String messageId = pushResult ? pushResponse.getMessageId() : null;

                    // 记录推送日志
                    ReminderLogs reminderLog = new ReminderLogs();
                    reminderLog.setTaskId(task.getId());
                    reminderLog.setUserId(user.getUserId());
                    reminderLog.setDeviceId(user.getRemark().trim());
                    reminderLog.setMessageId(messageId);
                    reminderLog.setScheduledTime(new Date());
                    reminderLog.setStatus(pushResult ? "SENT" : "FAILED");
                    reminderLog.setCreatedAt(new Date());
                    reminderLog.setUpdatedAt(new Date());
                    reminderLogsService.insertReminderLogs(reminderLog);

                    if (pushResult) {
                        log.info("推送消息成功，用户：{}，设备ID：{}，任务：{}，消息ID：{}",
                                user.getUserName(), user.getRemark(), task.getTitle(), messageId);
                    } else {
                        log.error("推送消息失败，用户ID：{}，设备ID：{}", user.getUserId(), user.getRemark());
                        allSuccess = false;
                    }
                } catch (Exception e) {
                    log.error("推送消息失败，用户ID：{}，错误信息：{}", recipient.getUserId(), e.getMessage(), e);
                    allSuccess = false;
                }
            }

            return allSuccess;
        } catch (Exception e) {
            log.error("推送任务消息失败，任务ID：{}，错误信息：{}", task.getId(), e.getMessage(), e);
            return false;
        }
    }

    @Override
    public boolean pushTaskReminder(Long taskId) {
        try {
            Tasks task = tasksService.selectTasksById(taskId);
            if (task == null) {
                log.error("任务不存在，任务ID：{}", taskId);
                return false;
            }

            String title = "任务提醒：" + task.getTitle();
            String content = "请及时处理您的任务：" + task.getDescription();

            Map<String, Object> extras = new HashMap<>();
            extras.put("reminderType", "TASK_REMINDER");
            extras.put("reminderTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis()));

            // 推送消息
            return pushMessageToTaskRecipients(task, title, content, extras);
        } catch (Exception e) {
            log.error("推送任务提醒失败，任务ID：{}，错误信息：{}", taskId, e.getMessage(), e);
            return false;
        }
    }

    @Override
    public boolean pushTaskCreationNotice(Long taskId) {
        try {
            Tasks task = tasksService.selectTasksById(taskId);
            if (task == null) {
                log.error("任务不存在，任务ID：{}", taskId);
                return false;
            }

            String title = task.getTitle();
            String content = task.getDescription();

            Map<String, Object> extras = new HashMap<>();
            extras.put("noticeType", "TASK_CREATION");
            extras.put("creationTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(task.getCreatedAt()));

            return pushMessageToTaskRecipients(task, title, content, extras);
        } catch (Exception e) {
            log.error("推送任务创建通知失败，任务ID：{}，错误信息：{}", taskId, e.getMessage(), e);
            return false;
        }
    }

    @Override
    public boolean pushMessageToUsers(Long[] userIds, String messageTitle, String messageContent,
            Map<String, Object> extras) {
        try {
            if (userIds == null || userIds.length == 0) {
                log.warn("用户ID列表为空");
                return true;
            }

            boolean allSuccess = true;
            for (Long userId : userIds) {
                try {
                    SysUser user = userService.selectUserById(userId);
                    if (user == null) {
                        log.warn("用户不存在，用户ID：{}", userId);
                        continue;
                    }

                    // 检查用户是否有设备ID（存储在remark字段中）
                    if (user.getRemark() == null || user.getRemark().trim().isEmpty()) {
                        log.warn("用户没有设备ID，用户ID：{}，用户名：{}", userId, user.getUserName());
                        continue;
                    }

                    // 使用设备ID推送（从remark字段获取）
                    aliyunPushService.pushMessageToDevice(
                            user.getRemark().trim(), // 使用remark字段存储的设备ID
                            messageTitle,
                            messageContent,
                            extras != null ? extras : new HashMap<>());

                    log.info("推送消息成功，用户：{}，设备ID：{}", user.getUserName(), user.getRemark());
                } catch (Exception e) {
                    log.error("推送消息失败，用户ID：{}，错误信息：{}", userId, e.getMessage(), e);
                    allSuccess = false;
                }
            }

            return allSuccess;
        } catch (Exception e) {
            log.error("批量推送消息失败，错误信息：{}", e.getMessage(), e);
            return false;
        }
    }

    /**
     * 检查任务是否在有效期内
     * 
     * @param task 任务对象
     * @return true-有效期内，false-无效期内
     */
    private boolean isTaskValid(Tasks task) {
        Date now = new Date();

        // 检查任务是否激活
        if (task.getIsActive() == null || task.getIsActive() != 1) {
            log.debug("任务未激活，任务ID：{}", task.getId());
            return false;
        }

        // 检查生效开始时间（为空表示立即生效）
        if (task.getEffectiveStart() != null && now.before(task.getEffectiveStart())) {
            log.debug("任务尚未到生效开始时间，任务ID：{}，开始时间：{}，当前时间：{}",
                    task.getId(), task.getEffectiveStart(), now);
            return false;
        }

        // 检查生效结束时间（为空表示永久有效）
        if (task.getEffectiveEnd() != null && now.after(task.getEffectiveEnd())) {
            log.debug("任务已超过生效结束时间，任务ID：{}，结束时间：{}，当前时间：{}",
                    task.getId(), task.getEffectiveEnd(), now);
            return false;
        }

        return true;
    }
}